package cn.lml.lession.controller;



import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.lml.lession.common.constant.Constant;
import cn.lml.lession.common.util.Result;


@RestController
public class HelloController {
	private final static Logger logger = LoggerFactory.getLogger(HelloController.class);
	
	@Autowired
	public OAuth2RestTemplate oAuth2RestTemplate;

	
	@RequestMapping(value="/hello/{name}", method = RequestMethod.GET)
	public String hello(@PathVariable("name") String username){
		logger.debug("访问路径：/user/"+username);
		logger.info("hello "+username);
		return "hello "+username;
	}

	
	@RequestMapping(value="/xx", method = RequestMethod.GET)
	public Result xx(){
		
		OAuth2AccessToken cc = oAuth2RestTemplate.getAccessToken();
		
		return Result.ok().put("r",cc.getRefreshToken()).put("t",cc.toString());
	}
	
	@GetMapping("/user/logout")
	public void logout(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String accessToken=oAuth2RestTemplate.getAccessToken().getValue();
		/*Result result=oAuth2RestTemplate.postForObject("http://localhost:9093/oauth/logout?accessToken="+accessToken,null,Result.class,"");
		if(result==null) return Result.error();
		if(Constant.RESULT.CODE_YES.getValue().equals(result.get("code"))){
			session.invalidate();
		}
		return result;*/
		session.invalidate();
		response.sendRedirect("http://localhost:9093/oauth/exit?access_token="+accessToken);
	}
		
	
	
	@GetMapping("/")
    public String welcome() {
        return "welcome";
    }

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }
	
	
	
}
